﻿using CommonModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CommonUtils
{
    public static class HTTPRequestUtils
    {
        #region  Post

        public static string PostJson(string url, object data, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }

            string result = "";
            //创建一个HTTP请求 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //Post请求方式 
            request.Method = "POST";
            //内容类型
            request.Accept = "application/json;charset=utf-8";
            request.ContentType = "application/json;charset=utf-8";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //设置参数，并进行URL编码 
            if (data != null)
            {
                string json = JsonConvert.SerializeObject(data);
                byte[] bdata = Encoding.UTF8.GetBytes(json);
                request.ContentLength = bdata.Length;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bdata, 0, bdata.Length);
                    reqStream.Close();
                }
            }

            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容 
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;


        }

        public static string PostJsonString(string url, string data, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }

            string result = "";
            //创建一个HTTP请求 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //Post请求方式 
            request.Method = "POST";
            //内容类型
            request.Accept = "application/json;charset=utf-8";
            request.ContentType = "application/json;charset=utf-8";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //设置参数，并进行URL编码 
            if (!string.IsNullOrWhiteSpace(data))
            {
                string json = data;
                byte[] bdata = Encoding.UTF8.GetBytes(json);
                request.ContentLength = bdata.Length;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bdata, 0, bdata.Length);
                    reqStream.Close();
                }
            }

            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容 
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;


        }




        public static async Task<string> PostJsonAsync(string url, object data, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }

            string result = "";
            //创建一个HTTP请求 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //Post请求方式 
            request.Method = "POST";
            //内容类型
            request.Accept = "application/json;charset=utf-8";
            request.ContentType = "application/json;charset=utf-8";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //设置参数，并进行URL编码 
            if (data != null)
            {
                string json = JsonConvert.SerializeObject(data);
                byte[] bdata = Encoding.UTF8.GetBytes(json);
                request.ContentLength = bdata.Length;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bdata, 0, bdata.Length);
                    reqStream.Close();
                }
            }

            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容 
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = await reader.ReadToEndAsync();
            }
            return result;


        }

        public static string PostForm(string url, IDictionary<string, string> par = null, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143  Safari/537.36";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                var postData = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                byte[] data = requestEncoding.GetBytes(postData);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            var response = request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream(), requestEncoding);
            string ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            return ret;
        }
        public static async Task<string> PostFormAsync(string url, IDictionary<string, string> par = null, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143  Safari/537.36";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                var postData = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                byte[] data = requestEncoding.GetBytes(postData);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            var response = request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream(), requestEncoding);
            string ret = await sr.ReadToEndAsync();
            sr.Close();
            response.Close();
            return ret;
        }

        public static HttpWebResponse PostResponse(string url, IDictionary<string, string> par = null, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143  Safari/537.36";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                var postData = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                byte[] data = requestEncoding.GetBytes(postData);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            return response;
        }

        #endregion

        #region get

        public static async Task<string> GetAsync(string url, IDictionary<string, string> par = null)
        {
            string postDataStr = "";
            string ReqUrl = url;
            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                postDataStr = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                if (url.Contains("?"))
                {
                    ReqUrl = url + "&" + postDataStr;
                }
                else
                {
                    ReqUrl = url + "?" + postDataStr;
                }

            }


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ReqUrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = await myStreamReader.ReadToEndAsync();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }


        public static string Get(string url, IDictionary<string, string> par = null)
        {
            string postDataStr = "";
            string ReqUrl = url;
            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                postDataStr = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                if (url.Contains("?"))
                {
                    ReqUrl = url + "&" + postDataStr;
                }
                else
                {
                    ReqUrl = url + "?" + postDataStr;
                }

            }


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ReqUrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString =   myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }




        public static HttpWebResponse GetResponse(string url, IDictionary<string, string> par = null)
        {
            string postDataStr = "";
            string ReqUrl = url;
            //如果需要POST数据  
            if (!(par == null || par.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in par.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, par[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, par[key]);
                    }
                    i++;
                }
                postDataStr = string.Join("&", par.Select(
                p => string.Format("{0}={1}", p.Key, System.Web.HttpUtility.UrlEncode(p.Value))).ToArray());
                if (url.Contains("?"))
                {
                    ReqUrl = url + "&" + postDataStr;
                }
                else
                {
                    ReqUrl = url + "?" + postDataStr;
                }

            }


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ReqUrl);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return response;
        }


        #endregion


        #region 参数处理
        /// <summary>
        /// 创建参数字典
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Dictionary<string, string> CreateParameters(string key, string value)
        {
            Dictionary<string, string> par = new Dictionary<string, string>();
            par.Add(key, value);
            return par;
        }
        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="par"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Dictionary<string, string> AddParameter(this Dictionary<string, string> par, string key, string value)
        {
            par.Add(key, value);
            return par;
        }
        #endregion



        #region  https 忽略证书错误
        [Obsolete]
        public static async Task<string> PostJsonIgnoreCertAsync(string url, object data, Encoding requestEncoding = null, IDictionary<string, string> headers = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }

            string result = "";




            if (url.StartsWith("https"))
            {
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
            }

            //创建一个HTTP请求 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //Post请求方式 
            request.Method = "POST";
            //内容类型
            request.Accept = "application/json;charset=utf-8";
            request.ContentType = "application/json;charset=utf-8";
            if (headers != null)
            {
                foreach (var k in headers)
                {
                    request.Headers.Add(k.Key, k.Value);
                }
            }

         





            //设置参数，并进行URL编码 
            if (data != null)
            {
                string json = JsonConvert.SerializeObject(data);
                byte[] bdata = Encoding.UTF8.GetBytes(json);
                request.ContentLength = bdata.Length;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(bdata, 0, bdata.Length);
                    reqStream.Close();
                }
            }

            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容 
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = await reader.ReadToEndAsync();
            }
            return result;


        }


        #endregion
    }


    public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
    {
        public TrustAllCertificatePolicy()
        { }
        public bool CheckValidationResult(ServicePoint sp,
            System.Security.Cryptography.X509Certificates.X509Certificate cert,
            WebRequest req, int problem)
        {
            return true;
        }
    }
}
